package xin.config.web;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import xin.common.http.response.ErrorResponse;
import xin.core.ErrorConstant;
import xin.core.exception.BaseException;
import xin.core.exception.SysException;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <pre>
 * Global Exception Handler
 * </pre>
 *
 * @author lixin_ma@outlook.com
 * @version 1.0
 * @since 2018/7/28 23:59
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BadCredentialsException.class)
    @ResponseBody
    public ErrorResponse BadCredentialsExceptionHandler(HttpServletRequest req,BadCredentialsException e) throws Exception {
        e.printStackTrace();
        return ErrorResponse.builder()
                .success(Boolean.FALSE)
                .code(ErrorConstant.AUTH_BAD_CREDENTIALS)
                .msg("用户名或密码错误")
                .path(req.getRequestURI().toString())
                .time(LocalDateTime.now())
                .build();
    }

    @ExceptionHandler(value = SysException.class)
    @ResponseBody
    public ErrorResponse sysExceptionHandler(HttpServletRequest req, SysException e) throws Exception {
        return sysHandle(req,e);
    }

    private ErrorResponse sysHandle(HttpServletRequest req,BaseException e) throws Exception{
        e.printStackTrace();
        return ErrorResponse.builder()
                .success(Boolean.FALSE)
                .code(e.getCode())
                .msg(e.getMsg())
                .path(req.getRequestURI().toString())
                .time(LocalDateTime.now())
                .build();
    }
}
